<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      v-show="showSearch"
      :inline="true"
    >
      <el-form-item label="工种编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入工种编码"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['prs:jobs:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate(updateRow)"
          v-hasPermi="['prs:jobs:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['prs:jobs:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['prs:jobs:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="jobsList"
      @selection-change="handleSelectionChange"
      :height="maxHeight"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="工种编码"
        prop="code"
        width="180"
        align="center"
      />
      <el-table-column
        label="工种名称"
        prop="name"
        width="180"
        align="center"
      />

      <el-table-column label="系数" prop="ratio" width="140" align="center" />
      <el-table-column label="排序" prop="orderId" width="100" align="center" />
      <el-table-column label="状态" width="120" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="创建者"
        prop="createBy"
        align="center"
        width="120"
      >
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateDate"
        width="180"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['prs:jobs:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['prs:jobs:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工种配置对话框 -->
    <el-dialog
      :title="title"
      class="permise-set"
      :visible.sync="open"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工种名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系数" prop="ratio">
              <el-input v-model="form.ratio" placeholder="请输入系数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="orderId">
              <el-input-number
                v-model="form.orderId"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status" style="text-align: right">
              <el-switch
                v-model="form.status"
                active-value="0"
                inactive-value="1"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listJobs,
  dictMatching,
  delJobs,
  addJobs,
  updateJobs,
  exportJobs,
  listTeam,
} from "../../api/jobs";
//并行请求
import axios from "axios";
import { TranslateList } from "../../utils/production";
export default {
  name: "Jobs",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //所属车间
      optionsworkType: [],
      //班组
      optionsteam: [],
      //工种
      optionsJobs: [],
      //已选班组
      teamCode: "",
      // 总条数
      total: 0,
      // 最大高度
      maxHeight: null,
      // 工种表格数据
      jobsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        name: "",
        code: "",
        status: "",
      },
      // 表单参数
      form: {},
      //修改
      updateRow: null,
      // 表单校验
      rules: {
        name: [
          {
            required: true,
            trigger: "blur",
          },
        ],
        orderId: [
          {
            required: true,
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getDictionaryType().then(() => {
      this.getList();
    });
    this.getTeam("0");
    this.getDicts("sys_normal_disable").then((response) => {
      this.statusOptions = response.data;
      console.log(this.statusOptions);
    });
  },
  methods: {
    //字典数据
    getDictionaryType() {
      return new Promise((resolve) => {
        const self = this;
        //并行请求
        axios
          .all([
            dictMatching("prs_order_type"),
            dictMatching("prs_jobs_jobs"),
          ])
          .then(
            axios.spread(function (resWorkType, resJobs) {
              if (resWorkType.code == 200 && resJobs.code == 200) {
                self.optionsworkType = resWorkType.data;
                self.optionsJobs = resJobs.data;
                resolve();
              }
            })
          );
      });
    },

    //切换所属车间
    workTypeChange(value) {
      this.form.teamCode = "";
      this.teamCode = "";
      this.getTeam(value);
    },

    //班组
    getTeam(value) {
      listTeam({ workType: value }).then((res) => {
        if (res.code == 200) {
          this.optionsteam = res.rows;
          if (this.optionsteam.length > 0) {
            this.form.teamCode = this.optionsteam[0].code;
            this.teamCode = this.form.teamCode;
          }
        }
      });
    },

    //查询工种列表
    getList() {
      this.loading = true;
      listJobs(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          let list = response.rows;
          if (list.length > 0) {
            TranslateList(list, [
              {
                dictData: this.optionsworkType,
                needStr: "workType",
                strCn: "workTypeCn",
                dictValue: "dictValue",
                dictLabel: "dictLabel",
              },
              {
                dictData: this.optionsteam,
                needStr: "teamCode",
                strCn: "teamCodeCn",
                dictValue: "code",
                dictLabel: "name",
              },
              {
                dictData: this.optionsJobs,
                needStr: "jobs",
                strCn: "jobsCn",
                dictValue: "dictValue",
                dictLabel: "dictLabel",
              },
            ]).then((data) => {
              this.jobsList = data;
            });
          } else {
            this.jobsList = [];
          }
          this.total = response.total;
          this.loading = false;
          this.maxHeight = `${document.documentElement.clientHeight}` - 270;
        }
      );
    },

    // 工种状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      const self = this;
      self.form = row;
      this.$confirm(
        "确认要" + text + " " + row.name + " " + "工种吗?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateJobs(self.form);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        code: "",
        name: "",
        ratio: "",
        orderId: "",
        status: "0",
      };
      this.resetForm("form");
    },

    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    //重置按钮操作
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      if (selection.length == 1) {
        this.updateRow = selection[0];
      }
      this.ids = selection.map((item) => item.uniqueId);
      console.log(this.ids);
      // console.log(selection)
      this.single = selection.length != 1; //修改按钮状态
      this.multiple = !selection.length;
    },

    // 新增按钮操作
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工种";
    },

    //修改按钮操作
    handleUpdate(row) {
      this.reset();
      this.form = row;
      this.open = true;
      this.title = "修改工种";
    },

    // 提交按钮
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.code !== "") {
            updateJobs(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addJobs(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.reset();
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const uniqueId = row.uniqueId || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delJobs(uniqueId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有工种数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportJobs(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
<style lang="scss">
.permise-set {
  .el-checkbox {
    margin-right: 13px;
  }

  .el-tree {
    padding: 10px;
  }

  .el-input-number--medium {
    width: 100%;
  }

  .menu-set {
    .el-form-item__content {
      margin-left: 0px !important;
    }

    .set-top {
      margin-left: 30px;

      .tree-set {
        height: calc(100vh - 270px);
        overflow: auto;
        border: 1px solid #dcdfe6;
      }
    }
  }
}
</style>
